package com.google.gsaguide;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.SearchManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.SearchView;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.google.gsaguide.DAO.AmbassadorDAO;
import com.google.gsaguide.fragments.AboutFragment;
import com.google.gsaguide.fragments.AmbassadorsFragment;
import com.google.gsaguide.fragments.FAQFragment;
import com.google.gsaguide.fragments.NavigationDrawerFragment;
import com.google.gsaguide.fragments.ProgramFragment;
import com.google.gsaguide.fragments.SummitFragment;
import com.google.gsaguide.otherlibs.SystemBarTintManager;

import java.lang.reflect.Field;

public class MainActivity extends ActionBarActivity
        implements NavigationDrawerFragment.NavigationDrawerCallbacks {

    // TODO: Need to optimize and comment this code.

    public static final boolean DEBUG = true;

    // AmbassadorsFragment section code.
    public static final int PROGRAM_FRAGMENT = 1;

    // AmbassadorsFragment section code.
    public static final int SUMMIT_FRAGMENT = 2;

    // AmbassadorsFragment section code.
    public static final int AMBASSADORS_FRAGMENT = 3;

    // FAQFragment section code.
    public static final int FAQ_FRAGMENT = 4;

    // AboutFragment section code.
    public static final int ABOUT_FRAGMENT = 5;
    //Used to store the section titles.
    String[] title_section;
    DrawerLayout mDrawer;
    FrameLayout.LayoutParams mDrawerParams;
    SearchView searchView;
    // Fragment managing the behaviors, interactions and presentation of the navigation drawer.
    private NavigationDrawerFragment mNavigationDrawerFragment;
    //Used to store the last screen title. For use in {@link #restoreActionBar()}.
    private CharSequence mTitle;

    @Override
    @SuppressLint("NewApi")
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //SharedPreferences sPref = getSharedPreferences("settings", 0);
        //if(!sPref.getBoolean(SplashActivity.SPLASH_SCREEN, false))
        splashScreen();

        // Get the section titles from resources.
        title_section = getResources().getStringArray(R.array.title_section);

        setContentView(R.layout.activity_main);

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
            mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
            mDrawerParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);

            setTranslucentStatus(true);
            SystemBarTintManager tintManager = new SystemBarTintManager(this);
            tintManager.setStatusBarTintEnabled(true);
            tintManager.setStatusBarTintColor(getResources().getColor(R.color.GoogleBlue));

            mDrawerParams.setMargins(0, getStatusBarHeight() + getActionBarHeight(), 0, 0);
            mDrawer.setLayoutParams(mDrawerParams);
        }

        mNavigationDrawerFragment = (NavigationDrawerFragment)
                getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);

        // Change the title according to the first attached section.
        mTitle = title_section[NavigationDrawerFragment.DEFAULT_SELECTED_POSITION];

        // Set up the drawer.
        mNavigationDrawerFragment.setUp(
                R.id.navigation_drawer,
                (DrawerLayout) findViewById(R.id.drawer_layout));
    }

    @Override
    public void onNavigationDrawerItemSelected(int position) {
        // Use this switch to call a new fragment.
        FragmentManager fragmentManager = getSupportFragmentManager();
        switch (position) {
            case 0: // GSA Program
                fragmentManager.beginTransaction().replace(R.id.container, ProgramFragment.newInstance()).commit();
                break;
            case 1: // Summit
                fragmentManager.beginTransaction().replace(R.id.container, SummitFragment.newInstance()).commit();
                break;
            case 2: // Ambassadors 2014
                fragmentManager.beginTransaction().replace(R.id.container, AmbassadorsFragment.newInstance()).commit();
                break;
            case 3: // FAQ
                fragmentManager.beginTransaction().replace(R.id.container, FAQFragment.newInstance()).commit();
                break;
            case 4: // About
                fragmentManager.beginTransaction().replace(R.id.container, AboutFragment.newInstance()).commit();
                break;
        }

        //TODO: Remove this line after implement the fragments.
        mTitle = title_section[position];
        updateSearchHint();
    }

    // Called when a new section was attached.
    public void onSectionAttached(int number) {
        // Change the title according to the attached section.
        mTitle = title_section[number - 1];
    }

    public void restoreActionBar() {
        ActionBar actionBar = getSupportActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
        actionBar.setDisplayShowTitleEnabled(true);
        actionBar.setTitle(mTitle);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (!mNavigationDrawerFragment.isDrawerOpen()) {
            // Only show items in the action bar relevant to this screen
            // if the drawer is not showing. Otherwise, let the drawer
            // decide what to show in the action bar.
            getMenuInflater().inflate(R.menu.main, menu);

            restoreActionBar();
            setSearchViewParams(menu);
            return true;
        }
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.

        //Global
        int id = item.getItemId();
//        if (id == R.id.action_settings) {
//            return true;
//        }
        return super.onOptionsItemSelected(item);
    }

    public void splashScreen() {
        Intent intent = new Intent();
        intent.setClass(MainActivity.this, SplashActivity.class);
        startActivity(intent);
    }

    public void hideVirtualKeyboard() {
        InputMethodManager imm = (InputMethodManager) getBaseContext().getSystemService(Service.INPUT_METHOD_SERVICE);
        if (imm.isActive()) {
            View v = this.getCurrentFocus();
            if (v == null)
                return;
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }
    }

    public void setSearchViewParams(Menu menu) {
        SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
        searchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.menu_search));
        searchView.setQueryHint(getString(R.string.hint_search_FAQ));
        searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
        searchView.setMaxWidth(10000);
        searchView.setOnSearchClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getSupportActionBar().setDisplayShowTitleEnabled(false);
            }
        });
        searchView.setOnCloseListener(new SearchView.OnCloseListener() {
            @Override
            public boolean onClose() {
                hideVirtualKeyboard();
                getSupportActionBar().setDisplayShowTitleEnabled(true);
                return false;
            }
        });

        SearchView.SearchAutoComplete searchAutoComplete =
                (SearchView.SearchAutoComplete) searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text);
        searchAutoComplete.setHintTextColor(getResources().getColor(R.color.GoogleLightGray));
        searchAutoComplete.setTextColor(getResources().getColor(R.color.White));

        try {
            Field mCursorDrawableRes = TextView.class.getDeclaredField("mCursorDrawableRes");
            mCursorDrawableRes.setAccessible(true);
            mCursorDrawableRes.set(searchAutoComplete, 0); //This sets the cursor resource ID to 0 or @null which will make it visible on white background
        } catch (Exception e) {
        }

        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String s) {
                hideVirtualKeyboard();
                if (s.equals(""))
                    return false;
                searchFor(s);
                return true;
            }

            @Override
            public boolean onQueryTextChange(String s) {
                if (s.equals(""))
                    return false;
                searchFor(s);
                return true;
            }
        });
    }

    public void searchFor(String queryText) {
        AmbassadorDAO.getInstance(getBaseContext()).getByNameAndUniversity(queryText);
    }

    @TargetApi(19)
    private void setTranslucentStatus(boolean on) {
        Window win = getWindow();
        WindowManager.LayoutParams winParams = win.getAttributes();
        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        if (on) {
            winParams.flags |= bits;
        } else {
            winParams.flags &= ~bits;
        }
        win.setAttributes(winParams);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);

        if ((mDrawerParams != null) && (mDrawer != null) && (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT)) {
            mDrawerParams.setMargins(0, getStatusBarHeight() + getActionBarHeight(), 0, 0);
            mDrawer.setLayoutParams(mDrawerParams);
        }
    }

    public int getStatusBarHeight() {
        int result = 0;
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    public int getActionBarHeight() {
        TypedValue tv = new TypedValue();
        int actionBarHeight = 0;
        if (getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) {
            actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data, getResources().getDisplayMetrics());
        }
        return actionBarHeight;
    }

    public void updateSearchHint() {
        if (mTitle.equals(getString(R.string.hint_search_FAQ)))
            searchView.setQueryHint(getString(R.string.hint_search_FAQ));
        if (mTitle.equals(getString(R.string.hint_search_AMB)))
            searchView.setQueryHint(getString(R.string.hint_search_AMB));
    }

}
